<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\translation\providers;

/**
 * 翻译提供商抽象基类
 */
abstract class AbstractTranslateProvider
{
    protected $config;

    public function __construct($config)
    {
        $this->config = $config;
        $this->validateConfig();
    }

    /**
     * 翻译文本
     */
    abstract public function translate($text, $targetLanguage, $sourceLanguage = 'zh_CN');

    /**
     * 检测语言（可选实现）
     */
    public function detectLanguage($text)
    {
        throw new \Exception('Language detection not supported by this provider');
    }

    /**
     * 验证配置
     */
    abstract protected function validateConfig();

    /**
     * 发送HTTP请求
     */
    protected function sendRequest($url, $data = [], $method = 'POST', $headers = [])
    {
        $ch = curl_init();

        $defaultHeaders = [
            'Content-Type: application/json',
            'User-Agent: Knight-CMS-Translation/1.0'
        ];

        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_HTTPHEADER     => array_merge($defaultHeaders, $headers),
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if (!empty($data)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? json_encode($data) : $data);
            }
        } elseif ($method === 'GET' && !empty($data)) {
            $url .= '?' . http_build_query($data);
            curl_setopt($ch, CURLOPT_URL, $url);
        }

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error    = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new \Exception("HTTP请求失败: {$error}");
        }

        if ($httpCode !== 200) {
            throw new \Exception("HTTP请求失败，状态码: {$httpCode}");
        }

        return $response;
    }

    /**
     * 清理文本（移除HTML标签等）
     */
    protected function cleanText($text)
    {
        // 移除HTML标签
        $text = strip_tags($text);

        // 移除多余的空白字符
        $text = preg_replace('/\s+/', ' ', $text);

        // 去除首尾空格
        $text = trim($text);

        return $text;
    }

    /**
     * 分割长文本
     */
    protected function splitLongText($text, $maxLength = 5000)
    {
        if (mb_strlen($text) <= $maxLength) {
            return [$text];
        }

        $chunks    = [];
        $sentences = preg_split('/[。！？.!?]/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);

        $currentChunk = '';
        foreach ($sentences as $sentence) {
            if (mb_strlen($currentChunk . $sentence) > $maxLength) {
                if (!empty($currentChunk)) {
                    $chunks[]     = trim($currentChunk);
                    $currentChunk = $sentence;
                } else {
                    // 单个句子太长，强制分割
                    $chunks[]     = mb_substr($sentence, 0, $maxLength);
                    $currentChunk = mb_substr($sentence, $maxLength);
                }
            } else {
                $currentChunk .= $sentence;
            }
        }

        if (!empty($currentChunk)) {
            $chunks[] = trim($currentChunk);
        }

        return array_filter($chunks);
    }

    /**
     * 记录翻译日志
     */
    protected function logTranslation($text, $result, $targetLanguage, $sourceLanguage, $provider)
    {
        $logData = [
            'provider'           => $provider,
            'source_language'    => $sourceLanguage,
            'target_language'    => $targetLanguage,
            'source_text_length' => mb_strlen($text),
            'result_text_length' => mb_strlen($result),
            'timestamp'          => date('Y-m-d H:i:s'),
        ];

        // 这里可以记录到日志文件或数据库
        error_log('Translation: ' . json_encode($logData, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 处理翻译错误
     */
    protected function handleTranslationError($error, $provider)
    {
        $errorMessage = "翻译提供商 {$provider} 错误: {$error}";
        error_log($errorMessage);
        throw new \Exception($errorMessage);
    }

    /**
     * 验证语言代码
     */
    protected function validateLanguageCode($languageCode, $supportedLanguages)
    {
        if (!in_array($languageCode, $supportedLanguages)) {
            throw new \Exception("不支持的语言代码: {$languageCode}");
        }
    }

    /**
     * 格式化翻译结果
     */
    protected function formatResult($result)
    {
        if (is_array($result)) {
            return implode('', $result);
        }

        return trim($result);
    }

    /**
     * 获取配置值
     */
    protected function getConfig($key, $default = null)
    {
        return $this->config[$key] ?? $default;
    }

    /**
     * 检查配置是否存在
     */
    protected function hasConfig($key)
    {
        return isset($this->config[$key]) && !empty($this->config[$key]);
    }
}
